<?php

/*
 * This file contains functions to handle pages position in 
 * the menu. The code in this file makes it possible for the 
 * admin to navigate a page's position with arrows.
 * 
 * @author Jacob Pedersen <jaacib@gmail.com>
 *
*/

/*
 * @return Lowest index number that's not in use
*/
function page_nextIndex() {
	global $db, $pages_table;
	$highest_index = $db->get("SELECT `index` FROM $pages_table ORDER BY `index` DESC LIMIT 1");	
	return $highest_index['index'] + 1;
}

/*
 * Moves the given page up in the menu
*/
function page_moveUp($id) {
	global $db, $pages_table;
	// Retrieve index for current page
	$current_page = $db->get("SELECT `id`,`index` FROM $pages_table WHERE `id` = $id LIMIT 1");
	// Test if pages can be moved up (are there pages with smaller index)
	$cur_index = $current_page['index'];
	if ($db->count($pages_table, 'id', "`index` < $cur_index") > 0) {
		// Pages with smaller index found
		// Find page with closest smaller index (can you say that? xD)
		$other_page = $db->get("SELECT `id`,`index` FROM $pages_table 
			WHERE `index` < $cur_index ORDER BY `index` DESC LIMIT 1");
		if ($other_page != null) {
			// A page with bigger index found, now swap indexes with current page
			page_swapIndex($id, $other_page['id']);
		}	
	}
	else {
		// No pages found, we're not changing index
	}
}

/*
 * Moves the given page down in the menu
*/
function page_moveDown($id) {
	global $db, $pages_table;
	// Retrieve index for current page
	$current_page = $db->get("SELECT `id`,`index` FROM $pages_table WHERE `id` = $id LIMIT 1");
	// Test if pages can be moved down (are there pages with bigger index)
	$cur_index = $current_page['index'];
	if ($db->count($pages_table, 'id', "`index` > $cur_index") > 0) {
		// Pages with bigger index found
		// Find page with closest bigger index (can you say that? xD)
		$other_page = $db->get("SELECT `id`,`index` FROM $pages_table 
			WHERE `index` > $cur_index ORDER BY `index` LIMIT 1");
		if ($other_page != null) {
			// A page with bigger index found, now swap indexes with current page
			page_swapIndex($id, $other_page['id']);
		}	
	}
	else {
		// No pages found, we're not changing index
	}
}

/*
 * Swaps the two given pages indexes
*/
function page_swapIndex($p1, $p2) {
	global $db, $pages_table;
	$page1 = $db->get("SELECT `index` FROM $pages_table WHERE id = $p1");
	$page2 = $db->get("SELECT `index` FROM $pages_table WHERE id = $p2");
	// Pages' indexes found, swap them (first set page 1's index, then page 2's)
	$db->execute("UPDATE $pages_table SET `index` = $page2[index] WHERE `id` = $p1");
	$db->execute("UPDATE $pages_table SET `index` = $page1[index] WHERE `id` = $p2");
}

/*
 * @return The pages relative position in the menu 
*/
function page_menuPos($id) {
	global $db, $pages_table;
	$pages = $db->get_result("SELECT id FROM $pages_table ORDER BY `index` ASC");
	for ($i=0;$i<count($pages);$i++) {
		if ($pages[$i]['id'] == $id) {
			return $i + 1;
		}
	}
}


?>